package com.swordxu.yim.server.tool;

import com.alibaba.fastjson.JSON;
import com.swordxu.yim.server.dbproxy.model.Session;
import com.swordxu.yim.server.packet.base.Header;
import com.swordxu.yim.server.tool.mananger.ContactManager;
import com.swordxu.yim.server.tool.mananger.LoginMananger;
import com.swordxu.yim.server.utils.ProtocolConstant;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

/**
 * 消息解码业务处理类
 * Created by 徐晓明 on 2015/1/6.
 */
public class IMPacketDispatcher {
    public static void dispatch(String buffer, ChannelHandlerContext channel) {
        String result = null;
        if (buffer == null) {
            return ;
        }

        Header header = new Header();
        System.out.println(JSON.parseObject(buffer).get("header"));
        header = JSON.parseObject(JSON.parseObject(buffer).get("header").toString(), Header.class);
        int sid = header.getSid();
        int cid = header.getCid();

        //登录业务请求
        if(sid == ProtocolConstant.SID_LOGIN) {
            switch (cid) {
                //请求消息服务器ip
                case ProtocolConstant.CID_LOGIN_REQ_MSGSERVER:
                    LoginMananger.instance(channel).reqMsgServer(buffer);
                    break;
                //请求登录消息服务器
                case ProtocolConstant.CID_LOGIN_REQ_USERLOGIN:
                    LoginMananger.instance(channel).login(buffer);
                    break;
                //客户端请求登出消息服务器
                case ProtocolConstant.CID_LOGIN_REQ_LOGINOUT:
                    break;
            }
        }
        //好友相关业务请求处理
        if (sid == ProtocolConstant.SID_BUDDY_LIST) {
            switch (cid) {
                //获取部门列表请求
                case ProtocolConstant.CID_BUDDY_LIST_DEPARTMENT_REQUEST:
                    ContactManager.instance(channel).reqGetDepartments(buffer);
                    break;
                //获取所有联系人
                case ProtocolConstant.CID_BUDDY_LIST_ALL_USER_REQUEST:
                    ContactManager.instance(channel).reqGetAllContacts(buffer);
                    break;
            }
        }
    }

    /**
     * 登录消息服务器鉴权
     * @param skey
     * @return
     */
    public static boolean login(String skey) {
        Session session = Session.dao.findFirst("select * from t_session where skey = '" + skey + "'");
        if (session == null) {
            return false;
        } else {
            return true;
        }
    }
}
